package com.tanhua.admin.service;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.EditorKit;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    public void analysis() throws ParseException {

        //获取当日时间
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //获取昨日时间
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");//工具类

        //新注册用户数
        Integer numLogin = logMapper.queryByTypeAndLogTime("0102", today);

        //用户今日登录数
        Integer regNum = logMapper.queryByTypeAndLogTime("0101", today);

        //活跃用户数regNum
        Integer numAct = logMapper.queryByLogTime(today);

        //次日留存用户数
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);

        //根据日期查询统计表数据是否存在
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(today);
        QueryWrapper<Analysis> qw=new QueryWrapper<>();
        qw.eq("record_date",today);
        Analysis analysis = analysisMapper.selectOne(qw);
        if (analysis==null){
            //不存在 保存新数据
            analysis=new Analysis();
            analysis.setNumRetention1d(numRetention1d);
            analysis.setNumLogin(numLogin);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(numAct);
            analysis.setRecordDate(recordDate);

            analysisMapper.insert(analysis);
        }else {
            //存在， 更新
            analysis.setNumRetention1d(numRetention1d);
            analysis.setNumLogin(numLogin);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(numAct);
            analysisMapper.updateById(analysis);
        }





    }
}
